import React, { Component } from "react";
import YKNav from "../nav/YKNav";
import SearchInput from "../searchInput/SearchInput";
import "./Category.scss"
import { getCategories } from "../../data/api"
import {withRouter} from "react-router-dom"
class Category extends Component {

  state = {
    categories:[],// 全部的分类的信息 
    select_index:0,
    rightContent:[] // 右边的内容项
  }
  async componentDidMount(){
    let res = await getCategories();
    console.log(res);
    let message = res.message||[]
    this.setState({
      categories:message,
      rightContent:message[0]
    })
  }
  handleItemClick=(e) => {
    let {index} = e.target.dataset;
    // console.log(index);
    index = parseInt(index);
    this.setState({
      select_index:index,
      rightContent:this.state.categories[index]
    })
  }
  // 分类菜单右边点击跳转逻辑
  handleProductItemClick = (cid) => {
    this.props.history.push("goodList?cid="+cid);
  }
  
  
  render() {
    return (
      <div className="ykCategory">
        <YKNav title="商品分类" left={false}></YKNav>
        <SearchInput></SearchInput>
        <div className="ykCategoryContent">
          {/* 左边的目录区开始 */}
          <div className="categoryContentLeft" onClick={this.handleItemClick}>
              {
                this.state.categories.map((c,index)=>{
                  return <div 
                  data-index={index}
                  className={this.state.select_index===index?"contentLeftItem active":"contentLeftItem"} key={c.cat_id}>
                    {c.cat_name}
                  </div>
                })
              }
          </div>
          {/* 左边的目录区结束 */}
          {/* 右边的内容区开始 */}
          <div className="categoryContentRight">
          {
            this.state.rightContent.children&&this.state.rightContent.children.map((v,i)=>{
              return <div className="contentRightItem" key={v.cat_id}>
                  <div className="rightItemTitle">
                    /{v.cat_name}/
                  </div>
                  {/* 商品列表开始 */}
                  <div className="rightItemList">
                    {
                      v.children&&v.children.map((vv=>{
                        return <div className="listProductItem" key={vv.cat_id} onClick={this.handleProductItemClick.bind(this,vv.cat_id)}>
                          <div className="imgWrapper">
                            <img src={vv.cat_icon} alt=""/>
                          </div>
                          <div className="title">
                            {vv.cat_name}
                          </div>
                        </div>
                      }))
                    }
                  </div>
                  {/* 商品列表结束 */}

              </div>
            })
          }
          </div>
          {/* 右边的内容区结束 */}
        </div>
      </div>
    );
  }
}
export default withRouter(Category)